from flask import Flask, render_template, request, redirect, Blueprint

student_blueprint = Blueprint('student', __name__)

students = [
    {'name': '张三', 'chinese': '65', 'math': '65', 'english': '65'},
    {'name': '李四', 'chinese': '65', 'math': '65', 'english': '65'},
    {'name': '王五', 'chinese': '65', 'math': '65', 'english': '65'},
    {'name': '赵六', 'chinese': '65', 'math': '65', 'english': '65'},
]


# 路由
@student_blueprint.route('/student')
def add_student():
    return render_template('add_student.html')


@student_blueprint.route('/admin')
def student_admin():
    return render_template('student_admin.html', students=students)


@student_blueprint.route('/add', methods=["GET", "POST"])
def add():
    if request.method == 'POST':
        username = request.form.get('username')
        chinese = request.form.get('chinese')
        math = request.form.get('math')
        english = request.form.get('english')
        print('获取的学员信息', username, math, chinese, english)
        students.append({'name': username, 'chinese': chinese, 'math': math, 'english': english})
        return redirect('/student/admin')
    return render_template('add_student.html')


@student_blueprint.route('/delete')
def delete_student():
    username = request.args.get('name')
    # 找到学员并删除信息
    for stu in students:
        if stu['name'] == username:
            students.remove(stu)
    return redirect('/student/admin')


@student_blueprint.route('/change', methods=["GET", "POST"])
def change():
    # 先显示学员的数据，然后再浏览修改，提交到服务器保存
    username = request.args.get('name')

    if request.method == "POST":
        username = request.form.get('username')
        chinese = request.form.get('chinese')
        math = request.form.get('math')
        english = request.form.get('english')

        for stu in students:
            if stu['name'] == username:
                stu['math'] = math
                stu['chinese'] = chinese
                stu['english'] = english

        return redirect('/admin')
    for stu in students:
        if stu['name'] == username:
            # 需要在页面中渲染学生的成绩数据
            return render_template('change.html', student=stu)
